const Generator = require('yeoman-generator');
// const inquirer = require('inquirer'); // 命令行交互工具
const path = require('path');
const fs = require('fs');
// const ejs = require('ejs');

/**
 * @param startPath  起始目录文件夹路径
 * @returns {Array}
 */

const findPathSync = (startPath) => {
  // 过滤一些不需要创建的文件夹
  const isFilterDirectory = ['.git', 'node_modules'].map(__path => `${startPath}/${__path}`)

  const result=[];
  const join = path.join

  const finder = (path) => {
    if(isFilterDirectory.includes(path)) return false
    const files = fs.readdirSync(path);

    for(let i =0; i< files.length; i++) {
      const value = files[i]
      const fPath= join(path, value);
      const stats= fs.statSync(fPath);

      // 如果是文件夹则递归调用，查找子文件
      stats.isDirectory() && finder(fPath);

      // 找到具体文件去除文件前缀
      stats.isFile() && result.push(fPath);
    }
  }

  finder(startPath);
  return result;
}


module.exports = class extends Generator {
  prompting() {
    return this.prompt([{
      type: 'input',
      name: 'name',
      message: 'Your project name',
      default: this.appname
    }])
    .then(answers => {
      this.answers = answers;

      // console.log('this.answers_____', this.answers)
    })
  }
  writing() {
    // 模板目录
    const tempDir = path.join(__dirname, 'templates')
    const findRst = findPathSync(tempDir).map(fullPath => fullPath.split('templates/')[1])

    // 遍历模板，写入项目文件
    findRst.forEach(file => {
      this.fs.copyTpl(
        this.templatePath(file),
        this.destinationPath(file),
        this.answers
      )
    });

    console.log('findRst_____', findRst)
  }
}